package com.gljx.web.controller;

import com.gljx.constant.ActivitiKey;
import com.gljx.util.*;
import com.gljx.web.Entity.*;
import com.gljx.web.service.*;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/")
public class SubjectOneResultController {
	@Autowired
	private SubjectOneResultService subjectOneResultService;

	@Autowired
	private SubjectOneResultentryService  subjectOneResultentryService;

	@Autowired
	private SubjectOneRegService subjectOneRegService;

	@Autowired
	private SubjectOneRegentryService  subjectOneRegentryService;

	// 自动注入
	@Autowired
	private DepartmentService departmentService;

	@Autowired
	private CustomLogService customLogService;

	@Autowired
	private StudentService studentService;

	//自定义流程工具
	private Axamine axamine = new Axamine();

	//导入activiti工具
	ActitiviUtil activitiUtil = new ActitiviUtil();

	/**
	 * 查询科目一考试结果登记信息
	 * @param request
	 * @param fnumber
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/querySubjectOneResult/look.action")
	public String querySubjectOneResult(HttpServletRequest request, @RequestParam(value = "fnumber", defaultValue = "") String fnumber
			, @RequestParam(value = "fdescription", defaultValue = "") String fdescription
			, @RequestParam(value = "cfstudentname", defaultValue = "") String cfstudentname
			, @RequestParam(value = "beginTime", defaultValue = "") String beginTime
			, @RequestParam(value = "endTime", defaultValue = "") String endTime
			, @RequestParam(value = "type",defaultValue = "") String type
			, @RequestParam(value = "selectState",required = false,defaultValue = "-1")String selectState
			, @RequestParam(value = "cfexmaresult",defaultValue = "")String cfexmaresult)throws Exception{
		PageBean<SubjectOneResult> pb = new PageBean<>();
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		try {
			fnumber = fnumber.trim();//去空格
			fdescription = fdescription.trim();
			cfstudentname = cfstudentname.trim();
			beginTime=beginTime.trim();
			endTime=endTime.trim();
			if("1".equals(selectState)){//如果传过来的标记为1 所以业务日期为空默认查询全部
				pb = getPageBean(request,user.getFcompanyid(),fnumber,fdescription,cfstudentname,null,null,cfexmaresult);
			}else{
				//默认时间
				if ("".equals(beginTime) && "".equals(endTime)) {
					beginTime = TimeFormat.getMonth();
					endTime = TimeFormat.getNowTime();
				}
				//获取分页
				pb = getPageBean(request,user.getFcompanyid(),fnumber,fdescription,cfstudentname,beginTime,endTime,cfexmaresult);
			}
			//计数器
			int i = 0;
			//缓存需要删除的序列
			List<Integer> tem = new ArrayList<>();
			//获取当前分页的值
			List<SubjectOneResult> subjectOneResultList = pb.getBeanList();
			//把获取到的数据传回页面
			if(cfstudentname.equals("")){
				cfstudentname=null;
			}

			if ("".equals(cfexmaresult)||"0".equals(cfexmaresult)){
				cfexmaresult=null;
			}

			for (SubjectOneResult subjectOneResult : subjectOneResultList) {
				//获取子类信息
				List<SubjectOneResultentry> subjectOneResultentries = subjectOneResultentryService.selSubjectOneResultentryByParentIdWithcfexmaresult(subjectOneResult.getFid(),cfstudentname,cfexmaresult);
				//放入集合
				subjectOneResult.setSubjectOneResultentryList(subjectOneResultentries);
			}
			//生成信息总数
			String messageAmount="共有"+pb.getTr()+"条信息";
			//返回界面的搜索条件
			request.setAttribute("messageAmount",messageAmount);
			request.setAttribute("fnumber", fnumber);
			request.setAttribute("fdescription", fdescription);
			request.setAttribute("cfstudentname", cfstudentname);
			request.setAttribute("beginTime", beginTime);
			request.setAttribute("endTime", endTime);
			request.setAttribute("subjectOneResultList", subjectOneResultList);
			request.setAttribute("pb", pb);
			request.setAttribute("type",type);
			request.setAttribute("selectState",selectState);
			request.setAttribute("cfexmaresult",cfexmaresult);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "backHome/examManage/subjectOneResult/subjectOneResultList";
	}


	/**
	 * 科目一考试登记字段筛选
	 * @param p
	 * @param request
	 * @return
	 */
	@RequestMapping("/subjectOutList")
	@ResponseBody
	public Object subjectOutList(@RequestBody(required=true) Map<String,Object> p, HttpServletRequest request){
		ArrayList<String> arr= (ArrayList<String>) p.get("outList");
		request.getSession().setAttribute("subjectOutList",arr);
		return arr;
	}





	/**
	 * 跳转到增加科目一考试结果登记信息页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/intoAddSubjectOneResult")
	public String intoSubjectOneResult(HttpServletRequest request,@RequestParam(value="type",required=false) String type)throws Exception{
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		//获取组织
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
	    /*获取当前时间*/
		String createTime = TimeFormat.timeFormat(new Date());
		//获取上一个编码
		/* String number = subjectOneResultService.selectFnumber(user.getFcompanyid());*/
		//获取编码
		//获取当前时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//业务时间
		String time = sdf.format(new Date());
		String fnumber = GetFnumber.fnumbers("OF");
		request.setAttribute("user", user);
		request.setAttribute("createTime", createTime);
		request.setAttribute("department", department);
		request.setAttribute("fnumber", fnumber);
		request.setAttribute("type",type);
		request.setAttribute("time",time);
		return "backHome/examManage/subjectOneResult/addSubjectOneResult";
	}

	/**
	 * 根据考试日期和车型查找考试的学员
	 * @param cfcartype
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/selStudentsBySubscribedOne")
	public Object selStudentsBySubscribedOne(HttpServletRequest request,String fbizdate,String cfcartype,String name)throws Exception{
		if(cfcartype != null){
			cfcartype=cfcartype.trim();
		}
		if(fbizdate !=null){
			fbizdate=fbizdate.trim();
		}
		if(name != null){
			name= name.trim();
		}

		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		if(name != null){
			if(name.equals("")){
				name = null;
			}
		}
		//首先查找对应日期和车型已经登记过却审核的科目一考试登记的单据
		List<SubjectOneReg> subjectOneRegList=subjectOneRegService.selSubjectOneRegByfbizdate(user.getFcompanyid(),fbizdate, cfcartype,null);
		List<SubjectOneRegentry> subjectOneRegentryList=new ArrayList<>();
		if(subjectOneRegList.size() != 0){
			for (SubjectOneReg subjectOneReg : subjectOneRegList) {
				List<SubjectOneRegentry> list=new ArrayList<>();
				list=subjectOneRegentryService.selSubjectOneRegByParentId(subjectOneReg.getFid(),name);
				for (SubjectOneRegentry subjectOneRegentry : list) {
					subjectOneRegentryList.add(subjectOneRegentry);
				}
			}
		}
		//防止出现重复的数据 做去重操作
		for (int i = 0; i <subjectOneRegentryList.size() ; i++) {
			for (int j = subjectOneRegentryList.size() -1; j >i ; j--) {
				if(subjectOneRegentryList.get(i).getCfstudentid().equals(subjectOneRegentryList.get(j).getCfstudentid())){
					subjectOneRegentryList.remove(j);
				}
			}
		}
		return subjectOneRegentryList;
	}
	/**
	 * 增加科目一考试结果登记
	 * @param request
	 * @param subjectOneResult
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/addSubjectOneResult")
	public String addSubjectOneResult(HttpServletRequest request,SubjectOneResult subjectOneResult)throws Exception{
		String [] stuid=request.getParameterValues("stuid");
		String [] stucfzkzmbh=request.getParameterValues("stucfzkzmbh");
		String [] stufnumber=request.getParameterValues("stufnumber");
		String [] stuname=request.getParameterValues("stuname");
		String [] stucfidcardno=request.getParameterValues("stucfidcardno");
		String [] stucfsex=request.getParameterValues("stucfsex");
		for (int i = 0; i < stucfsex.length; i++) {
			if(stucfsex[i].equals("男")){
				stucfsex[i]="1";
			}else{
				stucfsex[i]="2";
			}
		}
		String [] stucfsjhm=request.getParameterValues("stucfsjhm");
		String [] stucflxdh=request.getParameterValues("stucflxdh");
		String [] stucfslzjcxdh=request.getParameterValues("stucfslzjcxdh");
		String [] stucfclazzName=request.getParameterValues("stucfclazzName");
		String [] stucfamount=request.getParameterValues("stucfamount");
		String [] stucfreceived=request.getParameterValues("stucfreceived");
		String [] stucfarrearage=request.getParameterValues("stucfarrearage");
		String [] stucffavorable=request.getParameterValues("stucffavorable");
		String [] stucfvip=request.getParameterValues("stucfvip");
		String [] stucflocal=request.getParameterValues("stucflocal");
		for (int i = 0; i < stucflocal.length; i++) {
			if(stucflocal[i].equals("本地")){
				stucflocal[i]="1";
			}else if(stucflocal[i].equals("外地")){
				stucflocal[i]="2";
			}else{
				stucflocal[i]="3";
			}
		}
		String [] stucfexamresult=request.getParameterValues("stucfexamresult");
		String [] stucfremark=request.getParameterValues("stucfremark");
		/*获取uuid*/
		String uuid = GetFid.UUIDIntoFid();
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		subjectOneResult.setFid(uuid);
		//公司id
		subjectOneResult.setCfficompanyid(user.getFcompanyid());
		//控制单元id
		subjectOneResult.setFcontrolunitid(user.getFcompanyid());
		//获取当前修改时间
		String createTime = TimeFormat.timeFormat(new Date());
		//创建时间
		subjectOneResult.setFcreatetime(createTime);
		//创建人id
		subjectOneResult.setFcreatorid(user.getFid());
		//增加父类科目一考试结果登记信息
		int row1=0;
		int row2=0;
		row1= subjectOneResultService.addSubjectOneResult(subjectOneResult);
		//添加子类
		for (int i = 0; i < stuid.length; i++) {
			SubjectOneResultentry  subjectOneResultentry=new SubjectOneResultentry();
			subjectOneResultentry.setFseq(Long.valueOf(i+1));
			subjectOneResultentry.setFid(GetFid.UUIDIntoFid());
			subjectOneResultentry.setFparentid(subjectOneResult.getFid());
			subjectOneResultentry.setCfstudentid(stuid[i]);
			subjectOneResultentry.setCfzkzmh(stucfzkzmbh[i]);
			subjectOneResultentry.setCfstudentno(stufnumber[i]);
			subjectOneResultentry.setStudentName(stuname[i]);
			subjectOneResultentry.setCfidcardno(stucfidcardno[i]);
			subjectOneResultentry.setCfsex(Long.valueOf(stucfsex[i]));
			subjectOneResultentry.setCfmobile(stucfsjhm[i]);
			subjectOneResultentry.setCfphone(stucflxdh[i]);
			subjectOneResultentry.setCfsqzjcx(stucfslzjcxdh[i]);
			subjectOneResultentry.setCfclazz(stucfclazzName[i]);
			subjectOneResultentry.setCfreceivable(new BigDecimal(stucfamount[i]));
			subjectOneResultentry.setCfreceived(new BigDecimal(stucfreceived[i]));
			subjectOneResultentry.setCfarrearage(new BigDecimal(stucfarrearage[i]));
			subjectOneResultentry.setCffavorable(new BigDecimal(stucffavorable[i]));
			subjectOneResultentry.setCfvip(Long.valueOf(stucfvip[i]));
			subjectOneResultentry.setCfbdyd(Long.valueOf(stucflocal[i]));
			subjectOneResultentry.setCfexamresult(Long.valueOf(stucfexamresult[i]));
			subjectOneResultentry.setCfremark(stucfremark[i]);
			row2 +=subjectOneResultentryService.addSubjectOneResult(subjectOneResultentry);
			//添加学员服务日志
			customLogService.addLog("考试管理",  "新增了学员:"+subjectOneResultentry.getCfstudentno()+subjectOneResultentry.getStudentName()+
					",科目一考试结果登记!申请车型:"+subjectOneResultentry.getCfsqzjcx()+",考试日期:"+subjectOneResult.getFbizdate()+",单据编号:"+subjectOneResult.getFnumber(), subjectOneResultentry.getCfstudentid(), user.getFid());
		}
		String result="2";
		if( row1 > 0 && row2>0){
			result="1";
		}
		//添加日志
		customLogService.addLog("考试管理", TimeFormat.timeFormat(new Date()) + "科目一考试结果登记进行新增", null, user.getFid());
		return "redirect:/DrivingSys/intoAddSubjectOneResult?type="+result;
	}
	/**
	 * 跳转到修改科目一考试结果登记页面
	 * @param request
	 * @param fid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/intoUpdateSubjectOneResult")
	public String intoUpdateSubjectOneResult(HttpServletRequest request,
											 @RequestParam(value="fid",required=false) String fid)throws Exception{
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		//获取组织
		Department department = departmentService.queryAdminByFid(user.getFcompanyid());
		//获取父类信息
		SubjectOneResult subjectOneResult=subjectOneResultService.selectSubjectOneResultByFid(fid);
		if(subjectOneResult == null){
			return "/error/not_data";//单据不存在则跳转到错误页面
		}
		//查找子类信息
		subjectOneResult.setSubjectOneResultentryList(subjectOneResultentryService.selSubjectOneResultentryByParentId(subjectOneResult.getFid(),null));
		request.setAttribute("subjectOneResult", subjectOneResult);
		request.setAttribute("department",department);
		return"backHome/examManage/subjectOneResult/updateSubjectOneResult";
	}
	/**
	 * 修改科目一考试结果登记信息
	 * @param request
	 * @param subjectOneResult
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/updateSubjectOneResult")
	public String updateSubjectOneResult(HttpServletRequest request,SubjectOneResult subjectOneResult)throws Exception{
		String [] stuid=request.getParameterValues("stuid");
		String [] stucfzkzmbh=request.getParameterValues("stucfzkzmbh");
		String [] stufnumber=request.getParameterValues("stufnumber");
		String [] stuname=request.getParameterValues("stuname");
		String [] stucfidcardno=request.getParameterValues("stucfidcardno");
		String [] stucfsex=request.getParameterValues("stucfsex");
		for (int i = 0; i < stucfsex.length; i++) {
			if(stucfsex[i].equals("男")){
				stucfsex[i]="1";
			}else{
				stucfsex[i]="2";
			}
		}
		String [] stucfsjhm=request.getParameterValues("stucfsjhm");
		String [] stucflxdh=request.getParameterValues("stucflxdh");
		String [] stucfslzjcxdh=request.getParameterValues("stucfslzjcxdh");
		String [] stucfclazzName=request.getParameterValues("stucfclazzName");
		String [] stucfamount=request.getParameterValues("stucfamount");
		String [] stucfreceived=request.getParameterValues("stucfreceived");
		String [] stucfarrearage=request.getParameterValues("stucfarrearage");
		String [] stucffavorable=request.getParameterValues("stucffavorable");
		String [] stucfvip=request.getParameterValues("stucfvip");
		String [] stucflocal=request.getParameterValues("stucflocal");
		for (int i = 0; i < stucflocal.length; i++) {
			if(stucflocal[i].equals("本地")){
				stucflocal[i]="1";
			}else if(stucflocal[i].equals("外地")){
				stucflocal[i]="2";
			}else{
				stucflocal[i]="3";
			}
		}
		String [] stucfexamresult=request.getParameterValues("stucfexamresult");
		String [] stucfremark=request.getParameterValues("stucfremark");
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		//获取当前修改时间
		String updateTime = TimeFormat.timeFormat(new Date());
     /*   if (subjectOneResult.getCfbillstate()==5L ) {//如何状态为5则是审计 审核给出同意
        	subjectOneResult.setFauditorid(user.getFid());//设置审计人id
        	//修改父类
            subjectOneResultService.updateSubjectOneReusltByFid(subjectOneResult);
            //修改学员状态 科目一考试时间 和考试次数
            //获取该学员的科目一考试次数
            subjectOneResult.setSubjectOneResultentryList(subjectOneResultentryService.selSubjectOneResultentryByParentId(subjectOneResult.getFid(),null));
            List<SubjectOneResultentry> subjectOneResultList= subjectOneResult.getSubjectOneResultentryList();
            for (int i = 0; i < subjectOneResultList.size(); i++) {
            	Student _student=studentService.selectStudentById(subjectOneResultList.get(i).getCfstudentid());
				Student student=new Student();
				student.setCfkmykss(_student.getCfkmykss());
				student.setCfkmyqkcs(_student.getCfkmyqkcs());
				student.setFid(subjectOneResultList.get(i).getCfstudentid());
				if(student.getCfkmykss() == null){
					student.setCfkmykss(0L);
				}
				if(student.getCfkmyqkcs()==null){//科目一缺考次数
					student.setCfkmyqkcs(0L);
				}

				if(student.getCfkmykss() < 5 || student.getCfkmykss() == null){
					student.setCfkmykss(student.getCfkmykss()+1L);//次数加一
					if(subjectOneResultList.get(i).getCfexamresult() == 1){//合格
						student.setCfkmyherq(updateTime);//科目一合格日期
						student.setCfstudentstate(2L);//状态为科目一通过
					}else if(subjectOneResultList.get(i).getCfexamresult() == 2){//不合格
						student.setCfkmybjgsj(updateTime);//科目一不及格时间
						student.setCfstudentstate(3L);//状态为科目一未通过
					}else{//缺考
						student.setCfkmybjgsj(updateTime);
						student.setCfstudentstate(3L);//状态为科目一未通过
						student.setCfkmyqkcs(student.getCfkmyqkcs()+1L);//缺考次数加一
						student.setCfkmyksqksj(updateTime);//科目一缺考时间
					}
					//修改
					studentService.updateStudent(student);
				}else if(student.getCfkmykss() >= 5){//如果考试次数等于5则需要重新交钱考试 把学生状态设置为作废
					//设置学员状态 14为作废
					student.setCfstudentstate(14L);
					student.setCfkmybjgsj(subjectOneResult.getFbizdate());//设置科目一不及格时间
					//修改
					studentService.updateStudent(student);
				}
            }
        	return "redirect:/DrivingSys/querySubjectOneResult/look.action";
        }*/
		//把创建时间和业务日期清空不让修改
		subjectOneResult.setFcreatetime(null);
		//subjectOneResult.setFbizdate(null);
		subjectOneResult.setFlastupdateuserid(user.getFid());
		subjectOneResult.setFlastupdatetime(updateTime);
		//修改父类
		int row1 = subjectOneResultService.updateSubjectOneReusltByFid(subjectOneResult);
		//删除父类的子类
		subjectOneResultentryService.deleteSubjectOneResultentryByParentid(subjectOneResult.getFid(),null,null,null);
		//添加子类
		int row2 =0;
		for (int i = 0; i < stuid.length; i++) {
			SubjectOneResultentry  subjectOneResultentry=new SubjectOneResultentry();
			subjectOneResultentry.setFseq(Long.valueOf(i+1));
			subjectOneResultentry.setFid(GetFid.UUIDIntoFid());
			subjectOneResultentry.setFparentid(subjectOneResult.getFid());
			subjectOneResultentry.setCfstudentid(stuid[i]);
			subjectOneResultentry.setCfzkzmh(stucfzkzmbh[i]);
			subjectOneResultentry.setCfstudentno(stufnumber[i]);
			subjectOneResultentry.setStudentName(stuname[i]);
			subjectOneResultentry.setCfidcardno(stucfidcardno[i]);
			subjectOneResultentry.setCfsex(Long.valueOf(stucfsex[i]));
			subjectOneResultentry.setCfmobile(stucfsjhm[i]);
			subjectOneResultentry.setCfphone(stucflxdh[i]);
			subjectOneResultentry.setCfsqzjcx(stucfslzjcxdh[i]);
			subjectOneResultentry.setCfclazz(stucfclazzName[i]);
			subjectOneResultentry.setCfreceivable(new BigDecimal(stucfamount[i]));
			subjectOneResultentry.setCfreceived(new BigDecimal(stucfreceived[i]));
			subjectOneResultentry.setCfarrearage(new BigDecimal(stucfarrearage[i]));
			subjectOneResultentry.setCffavorable(new BigDecimal(stucffavorable[i]));
			subjectOneResultentry.setCfvip(Long.valueOf(stucfvip[i]));
			subjectOneResultentry.setCfbdyd(Long.valueOf(stucflocal[i]));
			subjectOneResultentry.setCfexamresult(Long.valueOf(stucfexamresult[i]));
			subjectOneResultentry.setCfremark(stucfremark[i]);
			row2 += subjectOneResultentryService.addSubjectOneResult(subjectOneResultentry);
			//添加学员的服务日志
			//添加学员服务日志
			customLogService.addLog("考试管理",  "修改了学员:"+subjectOneResultentry.getCfstudentno()+subjectOneResultentry.getStudentName()+
					",科目一考试结果登记!申请车型:"+subjectOneResultentry.getCfsqzjcx()+",考试日期:"+subjectOneResult.getFbizdate()+",单据编号:"+subjectOneResult.getFnumber(), subjectOneResultentry.getCfstudentid(), user.getFid());
		}
		String result ="";
		if(row1 >0 && row2 > 0){
			result ="1";
		}
		//添加日志
		customLogService.addLog("考试管理", TimeFormat.timeFormat(new Date()) + "科目一考试结果登记进行修改", null, user.getFid());
		return "redirect:/DrivingSys/querySubjectOneResult/look.action?type="+result;
	}

	/**
	 * 根据fid删除科目一考试信息
	 * @param request
	 * @param deleteId
	 * @param fid
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteSubjectOneResultByFid")
	public String deleteSubjectOneRegByFid(HttpServletRequest request, String[] deleteId,String fid)throws Exception{
		User user = (User) request.getSession().getAttribute("user");
		//删除记录
		if(fid==null || fid.equals("")){
			for (int i = 0; i < deleteId.length; i++) {
	            /*过滤为空的删除操作*/
				if (!deleteId[i].equals("")&&deleteId[i]!=null) {
					//根据fid查找单据编号
					SubjectOneResult subjectOneResult = subjectOneResultService.selectSubjectOneResultByFid(deleteId[i]);
					//删除历史或者进行中的流程
					activitiUtil.deleteTask(ActivitiKey.PUBLIC_KEY,subjectOneResult.getFnumber());
					subjectOneResultService.deleteSubjectOneResult(deleteId[i]);//删除父类
					subjectOneResultentryService.deleteSubjectOneResultentryByParentid(deleteId[i],user,subjectOneResult.getFbizdate(),(String)subjectOneResult.getFnumber());//删除子类
				}
			}
		}else{
			//根据fid查找单据编号
			SubjectOneResult subjectOneResult = subjectOneResultService.selectSubjectOneResultByFid(fid);
			//删除历史或者进行中的流程
			activitiUtil.deleteTask(ActivitiKey.PUBLIC_KEY,subjectOneResult.getFnumber());
			subjectOneResultService.deleteSubjectOneResult(fid);//删除父类
			subjectOneResultentryService.deleteSubjectOneResultentryByParentid(fid,user,subjectOneResult.getFbizdate(),(String)subjectOneResult.getFnumber());//删除子类
		}
		//添加日志
		customLogService.addLog("考试管理", TimeFormat.timeFormat(new Date()) + "科目一考试结果登记进行删除", null, user.getFid());
		return "redirect:/DrivingSys/querySubjectOneResult/look.action";
	}

	/**
	 * 提交科目一考试结果登记单据
	 * @param fid
	 * @param request
	 * @param fnumber
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "submitSubjectOneResultActiviti")
	@ResponseBody
	public Object submitSubjectOneResultActiviti(String fid, HttpServletRequest request, String fnumber)throws  Exception{
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		SubjectOneResult subjectOneResult =new SubjectOneResult();
		subjectOneResult.setFid(fid);
		subjectOneResult.setCfbillstate(4L);
		subjectOneResult.setFlastupdateuserid(user.getFid());
		//创建流程
		axamine.submissionProcess(fnumber);
		int row=subjectOneResultService.updateSubjectOneReusltByFid(subjectOneResult);
		//获取父类信息
		SubjectOneResult _subjectOneResult=subjectOneResultService.selectSubjectOneResultByFid(fid);
		//查找子类信息
		List<SubjectOneResultentry> subjectOneResultentries = subjectOneResultentryService.selSubjectOneResultentryByParentId(subjectOneResult.getFid(),null);
		if(subjectOneResultentries != null){
			for (int i = 0; i < subjectOneResultentries.size(); i++) {
				//添加学员服务日志
				customLogService.addLog("考试管理",  "提交了学员:"+subjectOneResultentries.get(i).getCfstudentno()+subjectOneResultentries.get(i).getStudentName()+
						",科目一考试结果登记!申请车型:"+subjectOneResultentries.get(i).getCfsqzjcx()+",考试日期:"+_subjectOneResult.getFbizdate()+",单据编号:"+_subjectOneResult.getFnumber(), subjectOneResultentries.get(i).getCfstudentid(), user.getFid());
			}

		}
		String result="failed";
		if(row >0){
			result="success";
		}
		Map<String,String> _map =new HashMap<>();
		_map.put("result",result);
		return _map;
	}


	/**
	 * 审核单据
	 * @param request
	 * @param fid
	 * @param agree
	 * @param auditcomment
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "checkSubjectOneResultActiviti")
	@ResponseBody
	public Object checkSubjectOneResultActiviti(HttpServletRequest request,String fnumber,String fid,String agree,String auditcomment)throws  Exception{
		//获取操作人信息
		User user = (User)request.getSession().getAttribute("user");
		SubjectOneResult subjectOneResult =new SubjectOneResult();
		//获取当前修改时间
		String updateTime = TimeFormat.timeFormat(new Date());
		String result ="failed";
		int row1=0;
		int row2=0;
		if(agree.equals("1")){//同意
			ServerResponse serverResponse = axamine.auditProcess(fnumber, agree, auditcomment);
			if(serverResponse.getStatus() == 1){//结束
				subjectOneResult.setFid(fid);
				subjectOneResult.setCfbillstate(5L);
				subjectOneResult.setFlastupdateuserid(user.getFid());
				subjectOneResult.setFauditorid(user.getFid());
				//修改父类
				row1 =subjectOneResultService.updateSubjectOneReusltByFid(subjectOneResult);
				//修改学员状态 科目一考试时间 和考试次数
				//获取该学员的科目一考试次数
				subjectOneResult.setSubjectOneResultentryList(subjectOneResultentryService.selSubjectOneResultentryByParentId(subjectOneResult.getFid(),null));
				List<SubjectOneResultentry> subjectOneResultList= subjectOneResult.getSubjectOneResultentryList();
				for (int i = 0; i < subjectOneResultList.size(); i++) {
					Student _student=studentService.selectStudentById(subjectOneResultList.get(i).getCfstudentid());
					Student student=new Student();
					student.setCfkmykss(_student.getCfkmykss());
					student.setCfkmyqkcs(_student.getCfkmyqkcs());
					student.setFid(subjectOneResultList.get(i).getCfstudentid());
					if(student.getCfkmykss() == null){
						student.setCfkmykss(0L);
					}
					if(student.getCfkmyqkcs()==null){//科目一缺考次数
						student.setCfkmyqkcs(0L);
					}
					if(student.getCfkmykss() < 5 || student.getCfkmykss() == null){
						student.setCfkmykss(student.getCfkmykss()+1L);//次数加一
						if(subjectOneResultList.get(i).getCfexamresult() == 1){//合格
							student.setCfkmyherq(updateTime);//科目一合格日期
							student.setCfstudentstate(2L);//状态为科目一通过
						}else if(subjectOneResultList.get(i).getCfexamresult() == 2){//不合格
							student.setCfkmybjgsj(updateTime);//科目一不及格时间
							student.setCfstudentstate(3L);//状态为科目一未通过
						}else{//缺考
							student.setCfkmybjgsj(updateTime);
							student.setCfstudentstate(3L);//状态为科目一未通过
							student.setCfkmyqkcs(student.getCfkmyqkcs()+1L);//缺考次数加一
							student.setCfkmyksqksj(updateTime);//科目一缺考时间
						}
						//修改
						row2=studentService.updateStudent(student);
					}/*else if(student.getCfkmykss() >= 5){//如果考试次数等于5则需要重新交钱考试 把学生状态设置为作废
						//设置学员状态 14为作废
						student.setCfstudentstate(14L);
						student.setCfkmybjgsj(subjectOneResult.getFbizdate());//设置科目一不及格时间
						//修改
						row2=studentService.updateStudent(student);
					}*/
				}
				//if(row1 >0 && row2 >0){//修改单据和修改学员都成功
				result = "success";
				//}
				//获取父类信息
				SubjectOneResult _subjectOneResult=subjectOneResultService.selectSubjectOneResultByFid(fid);
				//查找子类信息
				List<SubjectOneResultentry> subjectOneResultentries = subjectOneResultentryService.selSubjectOneResultentryByParentId(subjectOneResult.getFid(),null);
				if(subjectOneResultentries != null){
					for (int i = 0; i < subjectOneResultentries.size(); i++) {
						//添加学员服务日志
						customLogService.addLog("考试管理",  "审核了学员:"+subjectOneResultentries.get(i).getCfstudentno()+subjectOneResultentries.get(i).getStudentName()+
								",科目一考试结果登记!申请车型:"+subjectOneResultentries.get(i).getCfsqzjcx()+",考试日期:"+_subjectOneResult.getFbizdate()+",单据编号:"+_subjectOneResult.getFnumber(), subjectOneResultentries.get(i).getCfstudentid(), user.getFid());
					}

				}
			}else if(serverResponse.getStatus() == 2){
				result = "success";
			}else{

			}
		}else{
			ServerResponse serverResponse = axamine.auditProcess(fnumber, agree, auditcomment);
			if(serverResponse.getStatus() ==2){
				subjectOneResult.setFid(fid);
				subjectOneResult.setCfbillstate(3L);
				subjectOneResult.setFlastupdateuserid(user.getFid());
				subjectOneResult.setFauditorid(user.getFid());
				//修改父类
				row1 =subjectOneResultService.updateSubjectOneReusltByFid(subjectOneResult);
				if(row1 >0){
					result = "success";
				}
			}
		}
		Map<String,String> _map =new HashMap<>();
		_map.put("result",result);
		return _map;
	}

	/**
	 * 反审核科目一考试结果单据
	 * @param request
	 * @param fid
	 * @param againstAuditcomment
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "againstCheckSubjectOneResultActiviti")
	@ResponseBody
	public Object againstCheckSubjectOneResultActiviti(HttpServletRequest request,String fid,String fnumber,String againstAuditcomment )throws  Exception{
		//获取当前登录用户的信息
		User user =(User)request.getSession().getAttribute("user");
		String result ="falied";
		//将单据状态修改成保存状态3
		SubjectOneResult subjectOneResult = new SubjectOneResult();
		subjectOneResult.setFid(fid);
		subjectOneResult.setCfbillstate(3L);//保存状态
		subjectOneResult.setFauditorid(user.getFid());//设置反审计人id
		int row = subjectOneResultService.updateSubjectOneReusltByFid(subjectOneResult);
		axamine.againstAuditProcess(fnumber,againstAuditcomment);
		//获取父类信息
		SubjectOneResult _subjectOneResult=subjectOneResultService.selectSubjectOneResultByFid(fid);
		//查找子类信息
		List<SubjectOneResultentry> subjectOneResultentries = subjectOneResultentryService.selSubjectOneResultentryByParentId(subjectOneResult.getFid(),null);
		if(subjectOneResultentries != null){
			for (int i = 0; i < subjectOneResultentries.size(); i++) {
				//添加学员服务日志
				customLogService.addLog("考试管理",  "反审核了学员:"+subjectOneResultentries.get(i).getCfstudentno()+subjectOneResultentries.get(i).getStudentName()+
						",科目一考试结果登记!申请车型:"+subjectOneResultentries.get(i).getCfsqzjcx()+",考试日期:"+_subjectOneResult.getFbizdate()+",单据编号:"+_subjectOneResult.getFnumber(), subjectOneResultentries.get(i).getCfstudentid(), user.getFid());
			}

		}
		if (row > 0) {
			result = "success";
		}
		Map<String,String> _map =new HashMap<>();
		_map.put("result",result);
		return _map;
	}

	@SuppressWarnings("unchecked")
	/**
	 * 返回PageBean实体类  包括记录总数，页码，每页记录集等  dmz 20160921
	 * @return 返回PageBean实体类
	 * @throws Exception
	 */
	public PageBean<SubjectOneResult> getPageBean(HttpServletRequest request, String companyId, String fnumber,
												  String fdescription,String studentName,String beginTime, String endTime,String cfexamresult) throws Exception {

		int offset;//从第几条数据开始加载
		if (request.getParameter("pager.offset") == null) {
			offset = 0;
		} else {
			offset = Integer.parseInt(request.getParameter("pager.offset"));
		}
		//拼接SQL语句
		StringBuffer psql = new StringBuffer();

		psql.append(" SELECT distinct S.FID,S.FCREATORID,S.FCREATETIME,S.FLASTUPDATEUSERID,S.FLASTUPDATETIME,S.FCONTROLUNITID, "+
				"S.FNUMBER,to_char(S.FBIZDATE,'YYYY-MM-DD') FBIZDATE ,S.FHANDLERID,S.FDESCRIPTION,S.FAUDITORID,S.CFFICOMPANYID,S.CFBILLSTATE, "+
				"S.CFCARTYPE, E.NAME AS checkName,U.NAME AS createName "+
				"FROM CT_DS_SUBJECTONERESULT S  LEFT JOIN T_E_USER U ON U.FID=S.FCREATORID LEFT JOIN T_E_USER E ON E.FID=S.FAUDITORID "+
				" LEFT JOIN CT_DS_SUBJECTONERESULTENTRY S1 ON S1.FPARENTID = S.FID "+
				" LEFT JOIN CT_DS_STUDENT STU ON STU.FID = S1.CFSTUDENTID "+
				" WHERE S.FCONTROLUNITID='"+companyId+"' ");
		if (fnumber == null || fnumber.equals("")) {

		} else {
			psql.append( "AND S.FNUMBER LIKE '%" + fnumber + "%' ");
		}
		if (fdescription == null || fdescription.equals("")) {

		} else {
			psql.append( "AND S.FDESCRIPTION LIKE '%" + fdescription + "%'");
		}
		if (studentName == null || studentName.equals("")) {

		} else {
			psql.append( "AND STU.FNAME_L2 LIKE '%" + studentName + "%'");
		}
		if (beginTime == null || endTime == null) {
    		/*	 beginTime = TimeFormat.getMonth();
    		} else if(endTime == null || endTime.equals("")){
    		        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    		        endTime = sdf.format(new Date());
    			psql.append("AND TO_CHAR(S.FBIZDATE,'yyyy-MM-dd') BETWEEN '" + beginTime + "' AND '" + endTime + "'"); */
		}else{
			psql.append("AND TO_CHAR(S.FBIZDATE,'yyyy-MM-dd') BETWEEN '" + beginTime + "' AND '" + endTime + "'");
		}
          if (cfexamresult==null||cfexamresult.equals("")){

		  }else{
			  psql.append("AND s1.CFEXAMRESULT = '"+cfexamresult+"'");

		  }
		//psql.append(" ORDER BY to_char(S.FBIZDATE,'YYYY-MM-DD') DESC");
		psql.append(" ORDER BY FBIZDATE DESC");
		int psize = 50; //每页显示数
		int pindex = offset / psize;//+1  页码从0开始
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap = subjectOneResultService.selectPage(pindex, psql.toString(), psize);
		PageBean<SubjectOneResult> pb = new PageBean<>();
		pb.setPc(pindex); //页码
		Map<String, Object> paramMapCount = getPageBeanCount(psql.toString()); //取记录总数
		pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
		pb.setPs(psize);
		pb.setBeanList((List<SubjectOneResult>) paramMap.get("v_cur")); //每页数据集
		return pb;
	}

	/**
	 * 取记录总数 dmz 20160921
	 * @param psql  SQL语句
	 * @return Map
	 * @throws Exception
	 */
	public Map<String, Object> getPageBeanCount(String psql) throws Exception{

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap=subjectOneResultService.selectPageCount(psql);
		return paramMap;
	}

	/**
	 * 科目一考试结果登记 导出excel
	 * @param response
	 * @param request
	 * @param fnumber
	 * @param fdescription
	 * @param studentName
	 * @param beginTime
	 * @param endTime
	 */
	@RequestMapping(value = "/importSubjectOneResult")
	public void importSubjectOneResult(HttpServletResponse response, HttpServletRequest request
			, @RequestParam(value = "fnumber", defaultValue = "") String fnumber
			, @RequestParam(value = "fdescription", defaultValue = "") String fdescription
			, @RequestParam(value = "studentName", defaultValue = "") String studentName
			, @RequestParam(value = "beginTime", defaultValue = "") String beginTime
			, @RequestParam(value = "endTime", defaultValue = "") String endTime
	       ,@RequestParam(value = "cfexmaresult", defaultValue = "") String cfexmaresult){
		if("".equals(studentName)){
			studentName =null;
		}
		if ("".equals(cfexmaresult)){
			cfexmaresult=null;
		}
		//获取操作人信息
		User user = (User) request.getSession().getAttribute("user");
		//定义接收类型
		List<Object> data = new ArrayList<>();
		//查询数据
		List<SubjectOneResult> subjectOneResults=subjectOneResultService.selectSubjectOneResult(user.getFcompanyid(),fnumber,fdescription,beginTime,endTime);
		for (SubjectOneResult subjectOneResult :subjectOneResults){
			subjectOneResult.setSubjectOneResultentryList(subjectOneResultentryService.selSubjectOneResultentryByParentIdWithcfexmaresult(subjectOneResult.getFid(),studentName,cfexmaresult));
//			subjectOneResult.setSubjectOneResultentryList(subjectOneResultentryService.selSubjectOneResultentryByParentId(subjectOneResult.getFid(),studentName));
			for (int i = 0; i <subjectOneResult.getSubjectOneResultentryList().size() ; i++) {
				data.add(subjectOneResult.getFnumber());
				data.add(subjectOneResult.getFbizdate());
				data.add(subjectOneResult.getFdescription());
				data.add(subjectOneResult.getCheckName());
				data.add(subjectOneResult.getCreateName());
				if(subjectOneResult.getCfbillstate() == 3L){
					data.add("保存");
				}else if(subjectOneResult.getCfbillstate() == 4L){
					data.add("提交");
				}else{
					data.add("审核");
				}
				data.add(subjectOneResult.getSubjectOneResultentryList().get(i).getStudentName());
				data.add(subjectOneResult.getSubjectOneResultentryList().get(i).getCfstudentno());
				data.add(subjectOneResult.getSubjectOneResultentryList().get(i).getCfzkzmh());
				data.add(subjectOneResult.getSubjectOneResultentryList().get(i).getCfidcardno());
				if(subjectOneResult.getSubjectOneResultentryList().get(i).getCfsex() == 1L){
					data.add("男");
				}else if(subjectOneResult.getSubjectOneResultentryList().get(i).getCfsex() == 2L){
					data.add("女");
				}else{
					data.add("");
				}
				data.add(subjectOneResult.getSubjectOneResultentryList().get(i).getCfmobile());
				data.add(subjectOneResult.getSubjectOneResultentryList().get(i).getCfphone());
				if(subjectOneResult.getSubjectOneResultentryList().get(i).getCfvip() != null){
					if(subjectOneResult.getSubjectOneResultentryList().get(i).getCfvip() == 0L){
						data.add("是");
					}else if(subjectOneResult.getSubjectOneResultentryList().get(i).getCfvip() == 1L){
						data.add("否");
					}
				}else{
					data.add(null);
				}
				data.add(subjectOneResult.getSubjectOneResultentryList().get(i).getCfsqzjcx());
				if(subjectOneResult.getSubjectOneResultentryList().get(i).getCfbdyd() == 1L){
					data.add("本地");
				}else if(subjectOneResult.getSubjectOneResultentryList().get(i).getCfbdyd() == 2L){
					data.add("异地");
				}else if(subjectOneResult.getSubjectOneResultentryList().get(i).getCfbdyd() == 3L){
					data.add("学生");
				}else{
					data.add("");
				}
				if(subjectOneResult.getSubjectOneResultentryList().get(i).getCfexamresult() == 1L){
					data.add("合格");
				}else if(subjectOneResult.getSubjectOneResultentryList().get(i).getCfexamresult() == 2L){
					data.add("不合格");
				}else if(subjectOneResult.getSubjectOneResultentryList().get(i).getCfexamresult() == 3L){
					data.add("缺考");
				}
				data.add(subjectOneResult.getSubjectOneResultentryList().get(i).getCfremark());
				data.add(subjectOneResult.getSubjectOneResultentryList().get(i).getCfsqzjcx());
				data.add(subjectOneResult.getSubjectOneResultentryList().get(i).getCfclazz());
				data.add(subjectOneResult.getSubjectOneResultentryList().get(i).getCfreceivable());
				data.add(subjectOneResult.getSubjectOneResultentryList().get(i).getCfreceived());
				data.add(subjectOneResult.getSubjectOneResultentryList().get(i).getCfarrearage());
				data.add(subjectOneResult.getSubjectOneResultentryList().get(i).getCffavorable());
			}
		}
		//头部数据
		String head[] = {"单据编号", "业务日期", "参考信息", "单据状态","审核人名称", "制单人名称", "学员姓名","学员编码","准考证名编号","身份证号码",
				"性别","手机号码","电话","vip","申请车型","本地/异地","考试结果","备注","车型","班级",
				"应收", "已收","欠费","优惠"};
		//长度
		Integer length[] = {9000, 5000, 5000, 3000, 3000, 3000, 3000, 9000, 5000, 9000,
				3000, 5000, 3000, 3000, 3000, 3000, 3000, 3000, 5000, 3000,
				3000, 3000, 3000,3000};
		try {
			//导出Excel
			CommonExport.importExcel(response, "科目一考试结果登记" + TimeFormat.getNowTime2() + ".xls", "科目一考试结果登记", data, head, length);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

    /**
     * 科目一成绩模板导出
     * @param response
     * @param request
     */
	@RequestMapping(value = "/importSubjectTowResult")
	public void importSubjectTowResult(HttpServletResponse response, HttpServletRequest request) {
		//头部数据
		List<Object> data=new ArrayList<Object>();
		String head[] = {"学员姓名", "学习驾驶证明编号", "身份证明号码",
				"考试科目", "考试车型","考试日期","考试场地", "考试场次","考试成绩"};
		Integer length[] = {4500, 4500, 3000, 3000, 3000, 3000, 3000, 3000, 3000};
		try {
			//导出Excel
			CommonExport.importExcelTow(response, "学员成绩模板登记" + TimeFormat.getNowTime2() + ".xls", data, head, length);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
